/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package hermit.forum.db;


import hermit.forum.api.ForumCore;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Проверка на наличие файлов базы и их создание
 * работа с файлами SQL запросов
 * @author ~joMAjo~
 */
public class CreateDB {
    private FileFilter filefilter = new FileFilter() {
        public boolean accept(File file) {
            if (file.isFile()&&file.getName().toLowerCase().endsWith(".sql")) {
                return true;
            }
            return false;
        }
    };

    public void skanDB(ForumCore core) {
       // arch.extractFromJar("./JimBot_by-jo.jar", "./JB/");
       String dbPatch = core.dbPatch;
       if (new File(dbPatch).exists())
        try {

                Class.forName("org.sqlite.JDBC");
                String name="";
                boolean b=true;
                String SQLerr="";
                for (File file : new File(dbPatch).listFiles(filefilter)){
                    name = file.getName();
                    name = name.substring(0, name.lastIndexOf("."));
                  //  if (!testFile("./services/" + service + "/db/"+name+".db")){
                     Connection con=DriverManager.getConnection("jdbc:sqlite:"+dbPatch+"/"+name+".db");
                     PreparedStatement Pstat = null;
                     String SQLdump = loadText(file.getPath());
                    // File file= new File("./services/" + service + "/db/"+name+".sql");
                     String[] SQLrequest = SQLdump.split(";\n");
                     b=true;
                       for(int i_sql=0; i_sql<SQLrequest.length; i_sql++){
                           try {
                               if (testSQL(SQLrequest[i_sql])){
                                Pstat = (PreparedStatement)con.prepareStatement(SQLrequest[i_sql].replace("<br>", "\n"));
                                Pstat.execute();
                                Pstat.close();
                                core.getLogger().db("SQL: "+name+" - str#"+(i_sql+1)+" ok!");
                               }
                               } catch (SQLException e) {
                                   if (i_sql+1!=SQLrequest.length){
                                     SQLerr +=("!!!("+name+".sql) "+SQLrequest[i_sql]+"  - [ "+e.getMessage()+" ]\n");
                                     core.getLogger().db("!!!SQLОшибка ("+name+")#"+(i_sql+1)+" - [ "+e.getMessage()+" ]");
                                     b=false;
                                   }
                               }

                       }
                      if (b) file.renameTo(new File("./" + dbPatch+"/"+name+".ok"));
                         else
                             file.renameTo(new File("./" + dbPatch+"/"+name+".err"));
                      con.close();
                      con=null;
                    //  Log.info("Created new db: " + name+".db");
                    }
                    if (!SQLerr.equals(""))saveToFile("./" + dbPatch + "/SQLerr.txt",SQLerr);
           name=null;
           SQLerr=null;
      //   Log.info("Установка файлов базы завершена!");
         } catch (Exception ex) {
            ex.printStackTrace();
         }

    }
    /**
     * Загружает текст из файла
     * @param fname
     * @return
     */
    public static String loadText(String fname) {
       String s = "";
        try {
            BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(fname), "windows-1251"));
            while (r.ready())
             s = s + r.readLine() + "\n";
             r.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
     return s;
    }

    /**
     * сохраняет текст в файл
     * @param Path путь куда сохранять
     * @param text текст для сохранения
     * @throws java.lang.Exception
     */
    private void saveToFile(String Path,String text) throws Exception{
            File LogErr = new File (Path);
            if (LogErr.exists())LogErr.delete();
            OutputStreamWriter ow = new OutputStreamWriter(new FileOutputStream(Path,true),"windows-1251");
            ow.write(text);
            ow.close();
     }


     public boolean testSQL(String SQLcontent) {
           if(SQLcontent==null)return false;
           if("".equals(SQLcontent))return false;
           if(" ".equals(SQLcontent))return false;
           if("\n".equals(SQLcontent))return false;
           if("\r".equals(SQLcontent))return false;
           if("\n\r".equals(SQLcontent))return false;

           return true;

     }



}